import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:getxdemo/model/request_register.dart';
import 'package:getxdemo/utils/locale_util.dart';
import 'package:shared_preferences/shared_preferences.dart';



class SPUtil{

  static SharedPreferences sp(){
    return Get.find<SharedPreferences>();
  }


  static void saveSelectLang(Language language){
    sp().remove(SPKey.language);
    sp().setString(SPKey.language, json.encode(language.toJson()));
  }

  static Language? getLanguage() {
    return getModel(SPKey.language, (json) => Language.fromJson(json));
  }

  static T? getModel<T>(String spKey,JsonData<T> getValue){
    String? l = sp().getString(spKey);
    try {
      if(l == null){
        return null;
      }
      return getValue(jsonDecode(l));
    } catch (e) {
      debugPrint(e.toString());
    }
    return null;
  }

  static void saveUserInfo(UserEntity entity) {
    sp().remove(SPKey.userEntity);
    sp().setString(SPKey.userEntity, json.encode(entity.toJson()));
  }

  static UserEntity? getUserEntity(){
    return getModel(SPKey.userEntity, (json) => UserEntity.fromJson(json));
  }

}

typedef JsonData<T> = T Function(dynamic json);

class SPKey{
  /// 语言环境
  static const language = "language";

  /// 用户信息
  static const userEntity = "userEntity";
}